import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

import banner from "../config/banner.js"
import subNav from "../config/subNav.js"
import guide from "../config/guide.js"
import request from "../request/index.js"
export default new Vuex.Store({
	state: {
		banner,
		subNav,
		guide,
		vuex_exam: uni.getStorageSync('examStorage') || null,
		vuex_user: uni.getStorageSync('user') || null,
		vuex_unread_notice_count: uni.getStorageSync('vuex_unread_notice_count') ||
			null
	},
	mutations: {
		"SET_USER"(state, user) {
			state.vuex_user = user;
			uni.setStorage({
				key: 'user',
				data: user
			})
		},
		"UPDATE_USER"(state, user) {
			if (user === null)
				state.vuex_user = null
			else Object.keys(user).map(key => state.vuex_user[key] = user[key]);
			uni.setStorage({
				key: 'user',
				data: state.vuex_user
			})
		},
		"SET_UNREAD_NOTICE_COUNT"(state, count) {
			state.vuex_unread_notice_count = count;
			uni.setStorage({
				key: 'vuex_unread_notice_count',
				data: count
			})
		}
	},
	actions: {
		login({
			commit
		}, user) {
			return new Promise((resolve, reject) => {
				request.post('/base/appTeaLogin', user).then(res => {
					const {
						loginUserInfo,
						token
					} = res
					commit("SET_USER", {
						...loginUserInfo,
						token
					})
					resolve()
				}).catch(err => {
					console.log('err');
				});
			})
		},
		updateUser({
			commit
		}, user) {
			return new Promise((res, rej) => {
				commit("UPDATE_USER", user)
				res()
			})
		},
		updateUnreadNoticeCount({
			commit
		}, count) {
			commit("SET_UNREAD_NOTICE_COUNT", count)
			//#ifdef APP-PLUS
			plus.runtime.setBadgeNumber(count);
			//#endif
		}
	}
})
